package com.RuiJi.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * @author Twinkle
 * @PACKAGE_NAME: com.RuiJi.utils
 * @NAME: EmailUtils
 * @USER: Twinkle
 * @DATE: 2023/4/14
 * @TIME: 22:23
 * @YEAR: 2023
 * @MONTH: 04
 */
@Component
public class MyEmail {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender javaMailSerder;

    public String sendMail(String email, HttpSession session){
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(email);
        // 设置邮件的主题
        message.setSubject("登录验证码");
        // 设置邮件的正文
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(r);
        }
        String text = "您的验证码为：" + code + ",请勿泄露给他人。";


        message.setText(text);
        // 发送邮件
        try {
            javaMailSerder.send(message);
            return "发送成功";
        } catch (MailException e) {
            e.printStackTrace();
        }
        return "发送失败";

    }

}
